package com.lian.aieduc.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static String JWT_SECRET_KEY = "HOPE_MP";

    // 接收业务数据,生成token 并返回
    public static String generateToken(Map<String, Object> claims) {
        return JWT.create().withClaim("claims", claims).withExpiresAt(
            new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12)).sign(Algorithm.HMAC256(JWT_SECRET_KEY));
    }

    // 接收 token,验证 token,并返回业务数据
    public static Map<String, Object> parseToken(String token) {
        Map<String, Object> result = new HashMap<>();
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(JWT_SECRET_KEY)).build().verify(token);
        Map<String, Object> claims = decodedJWT.getClaim("claims").asMap();
        for (Map.Entry<String, Object> entry : claims.entrySet()) {
            if (entry.getValue() instanceof Integer integerValue) {
                result.put(entry.getKey(), integerValue.toString());
            } else if (entry.getValue() instanceof String stringValue) {
                result.put(entry.getKey(), stringValue);
            }
        }
        return result;
    }

    /**
     * 生成带有用户id的token
     * @param userId
     * @return
     */
    public static String generateTokenWithUserId(Long userId) {
        HashMap<String, Object> clamis = new HashMap<>();
        clamis.put("userId",userId);
       return generateToken(clamis);
    }

}
